package com.fzfnn.scrapbook.service.impl;

import com.fzfnn.scrapbook.entity.Journal;
import com.fzfnn.scrapbook.mapper.JournalMapper;
import com.fzfnn.scrapbook.service.JournalBasicService;
import com.fzfnn.scrapbook.service.PicturesService;
import com.fzfnn.scrapbook.util.R;
import com.fzfnn.scrapbook.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class JournalBasicSericeImpl implements JournalBasicService {
    @Autowired
    private JournalMapper journalMapper;
    @Autowired
    private PicturesService picturesService;
    @Autowired
    private RedisTemplate<String, String> redisMail;
    @Override
    public R createJournal(Journal journal, String token) throws IOException {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        if (journal == null) {
            return R.errorMsg("手账内容不能为空");
        }
        if (journal.getTitle() == null || journal.getTitle().isEmpty()) {
            return R.errorMsg("手账标题不能为空");
        }
        if (journal.getContent() == null || journal.getContent().isEmpty()) {
            return R.errorMsg("手账内容不能为空");
        }
        String imgurls = redisMail.opsForValue().get("user:" + userId + ":imageUrls");
        if (imgurls != null) {
            journal.setImgurl(imgurls);
        } else {
            journal.setImgurl("");
        }
        journal.setUserId(Integer.valueOf(userId));
        journal.setCreatedAt(TimeUtil.getNowTimestamp());
        journal.setUpdatedAt(TimeUtil.getNowTimestamp());
        if (journal.getIsPublic() == null) {
            journal.setIsPublic(1);
        }
        if (journal.getTag() != null && !journal.getTag().isEmpty()) {
            // 去除每个标签前后空格，并重新拼接字符串
            String[] tags = journal.getTag().split(",");
            List<String> trimmedTags = new ArrayList<>();
            for (String tag : tags) {
                String trimmed = tag.trim();
                if (!trimmed.isEmpty() && !trimmedTags.contains(trimmed)) {
                    trimmedTags.add(trimmed);
                }
            }
            String tagStr = String.join(",", trimmedTags);
            journal.setTag(tagStr);
        } else {
            journal.setTag("");
        }
        try {
            int result = journalMapper.insertJournal(journal);
            if (result > 0) {
                redisMail.opsForValue().getOperations().delete("user:" + userId + ":imageUrls");
                return R.successMsg("创建成功");
            } else {
                return R.errorMsg("创建失败，可能是数据库异常");
            }
        } catch (Exception e) {
            return R.errorMsg("创建日志失败，服务器错误");
        }
    }

    @Override
    public R updateJournal(Journal journal, String token) throws IOException {
        String userIdStr = redisMail.opsForValue().get("token:" + token);
        if (userIdStr == null) {
            return R.errorMsg("登录信息已过期，请重新登录");
        }
        Integer userId;
        try {
            userId = Integer.parseInt(userIdStr);
        } catch (NumberFormatException e) {
            return R.errorMsg("内部错误：无效的用户ID格式");
        }
        boolean hasUpdates = false;
        Map<String, Object> params = new HashMap<>();
        params.put("journalId", journal.getJournalId());
        params.put("userId", userId);
        if (journal.getTitle() != null && !journal.getTitle().isEmpty()) {
            params.put("title", journal.getTitle());
            hasUpdates = true;
        }
        if (journal.getContent() != null && !journal.getContent().isEmpty()) {
            params.put("content", journal.getContent());
            hasUpdates = true;
        }
        if (journal.getUpdatedAt() != null) {
            params.put("updatedAt", journal.getUpdatedAt());
            hasUpdates = true;
        }
        if (journal.getImgurl() != null && !journal.getImgurl().isEmpty()) {
            params.put("imgurl", journal.getImgurl());
            hasUpdates = true;
        }
        if (!hasUpdates) {
            return R.errorMsg("没有提供需要更新的字段");
        }
        int result = journalMapper.updateJournal(
                (String) params.getOrDefault("title", null),
                (String) params.getOrDefault("content", null),
                (Timestamp) params.getOrDefault("updatedAt", null),
                (String) params.getOrDefault("imgurl", null),
                (int) params.get("journalId"),
                (int) params.get("userId"),
                (String) params.getOrDefault("tag", null)
        );
        if (result > 0) {
            return R.successMsg("更新成功");
        } else {
            return R.errorMsg("更新失败");
        }
    }

    @Override
    public R deleteJournal(Integer journalId, String token) {
        String userIdStr = redisMail.opsForValue().get("token:" + token);
        if (userIdStr == null) {
            return R.errorMsg("登录信息已过期，请重新登录");
        }
        int result = journalMapper.deleteJournal(journalId, Integer.parseInt(userIdStr));
        if (result > 0) {
            return R.successMsg("删除成功");
        } else {
            return R.errorMsg("删除失败");
        }
    }
    @Override
    public R toggleVisibility(Integer journalId, String token) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            // 登录无效，默认未关注（或抛异常，由上层处理）
            return R.errorMsg("登录信息已过期，请重新登录");
        }
        int updated = journalMapper.toggleVisibility(journalId, Integer.parseInt(userId));
        if (updated > 0) {
            int visibility = journalMapper.getVisibility(journalId);
            if (visibility == 1){
                return R.successMsg("手账已可见");
            }else {
                return R.successMsg("手账已私密");
            }
        }
        return R.errorMsg("修改失败");
    }

}
